package com.byzk.p2p.admin.base.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.byzk.p2p.admin.admin.dto.SysUser;
import com.byzk.p2p.admin.admin.service.AdminService;
import com.byzk.p2p.admin.admin.vo.SecurityUser;
import com.byzk.p2p.admin.admin.vo.SystemRole;
import com.byzk.p2p.admin.system.service.MenuService;
import com.byzk.p2p.admin.system.vo.MenuItem;

/**
 * Spring Security 认证
 * @author suker.zhou
 */
public class AuthoritiesService implements UserDetailsService {

	@Autowired
	private AdminService adminService;
	
	@Autowired
	private MenuService menuService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if(StringUtils.isBlank(username)){
			throw new UsernameNotFoundException("Username can not be null");
		}
		SysUser admin = adminService.getByName(username.trim());
		
		if(null == admin){
			throw new UsernameNotFoundException("User not found");
		}
		
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		
		// 设置管理员角色
		if(admin.getGroupId() == 1){
			authorities.add(new SimpleGrantedAuthority(SystemRole.ROLE_ADMIN.name()));
		}
		List<MenuItem> menus=null;
		menus=menuService.getMenusByGroupId(admin.getGroupId());
		// 设置用户角色
		authorities.add(new SimpleGrantedAuthority(SystemRole.ROLE_USER.name()));
		
		// 在 session 中缓存用户信息
		return new SecurityUser(admin,menus,admin.getUserName(), admin.getPassword(),
				authorities, adminService.getAdminDao());
	}

}
